import React, { useState, useEffect } from 'react';
import Header from './components/Header';
import ApiTabs from './components/ApiTabs';
import ResultDisplay from './components/ResultDisplay';
import HistoryList from './components/HistoryList';
import './App.css';

function App() {
    // 初始状态示例
    const [state, setState] = useState({
        processCount: 3,
        resourceTypeCount: 2,
        maxMatrix: [
            [7, 5],
            [3, 2],
            [9, 0]
        ],
        allocationMatrix: [
            [0, 1],
            [2, 0],
            [3, 0]
        ],
        availableVector: [3, 3]
    });

    const [result, setResult] = useState(null);
    const [history, setHistory] = useState([]);

    // 从localStorage加载历史记录
    useEffect(() => {
        const savedHistory = localStorage.getItem('bankerAlgorithmHistory');
        if (savedHistory) {
            try {
                setHistory(JSON.parse(savedHistory));
            } catch (e) {
                console.error('Failed to parse history from localStorage', e);
            }
        }
    }, []);

    // 保存历史记录到localStorage
    const addHistory = (newItem) => {
        const newHistory = [newItem, ...history.slice(0, 9)]; // 保留最近10条记录
        setHistory(newHistory);
        localStorage.setItem('bankerAlgorithmHistory', JSON.stringify(newHistory));
    };

    // 从历史记录恢复请求
    const restoreHistory = (item) => {
        setState({
            ...item.input,
            deadlockProcesses: item.input.deadlockProcesses || [] // 确保不保留死锁进程选择
        });

        setResult({
            type: item.type === '安全检测解释' ? 'explain' : 'diagnose',
            data: item.output,
            state: {...item.input},
            deadlockProcesses: item.input.deadlockProcesses || []
        });
    };

    return (
        <div className="app">
            <Header />

            <div className="main-content">
                <div className="input-section">
                    <div className="config-controls">
                        <label>
                            进程数量:
                            <input
                                type="number"
                                min="1"
                                max="10"
                                value={state.processCount}
                                onChange={(e) => {
                                    const count = Math.min(Math.max(parseInt(e.target.value, 10), 1, 10));
                                    setState({
                                        ...state,
                                        processCount: count,
                                        maxMatrix: resizeMatrix(state.maxMatrix, count, state.resourceTypeCount),
                                        allocationMatrix: resizeMatrix(state.allocationMatrix, count, state.resourceTypeCount)
                                    });
                                }}
                            />
                        </label>

                        <label>
                            资源类型:
                            <input
                                type="number"
                                min="1"
                                max="5"
                                value={state.resourceTypeCount}
                                onChange={(e) => {
                                    const count = Math.min(Math.max(parseInt(e.target.value, 10), 1), 5);
                                    setState({
                                        ...state,
                                        resourceTypeCount: count,
                                        maxMatrix: resizeMatrix(state.maxMatrix, state.processCount, count),
                                        allocationMatrix: resizeMatrix(state.allocationMatrix, state.processCount, count),
                                        availableVector: resizeVector(state.availableVector, count)
                                    });
                                }}
                            />
                        </label>
                    </div>

                    <ApiTabs
                        state={state}
                        setResult={setResult}
                        onStateChange={setState}
                        addHistory={addHistory}
                    />
                </div>

                <div className="result-section">
                    <ResultDisplay result={result} />
                    <HistoryList
                        history={history}
                        onRestore={restoreHistory}
                    />
                </div>
            </div>
        </div>
    );
}

// 辅助函数：调整矩阵大小
function resizeMatrix(matrix, rows, cols) {
    const newMatrix = Array(rows).fill().map(() => Array(cols).fill(0));

    for (let i = 0; i < Math.min(rows, matrix.length); i++) {
        for (let j = 0; j < Math.min(cols, matrix[i].length); j++) {
            newMatrix[i][j] = matrix[i][j];
        }
    }

    return newMatrix;
}

// 辅助函数：调整向量大小
function resizeVector(vector, size) {
    const newVector = Array(size).fill(0);

    for (let i = 0; i < Math.min(size, vector.length); i++) {
        newVector[i] = vector[i];
    }

    return newVector;
}

export default App;